package com.ss.android.common.app.permission;

import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;

import com.bytedance.common.utility.Logger;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public abstract class PermissionsResultAction {
    private static final String TAG = PermissionsResultAction.class.getSimpleName();

    public final Set<String> mPermissions;
    private Looper mLooper;

    public PermissionsResultAction() {
        this.mPermissions = new HashSet(1);
        this.mLooper = Looper.getMainLooper();
    }

    public abstract void onGranted();

    public abstract void onDenied(String arg1);

    protected final synchronized void registerPermissions(@NonNull String[] permissions) {
        Collections.addAll(this.mPermissions, permissions);
    }

    protected final synchronized boolean onResult(@NonNull String permission, int result) {
        if (result == 0) {
            return this.onResult(permission, Permissions.GRANTED);
        } else {
            return this.onResult(permission, Permissions.DENIED);
        }
    }

    protected final synchronized boolean onResult(@NonNull String permission, Permissions permissions) {
        boolean v0 = true;
        this.mPermissions.remove(permission);
        if (permissions == Permissions.GRANTED) {
            if (this.mPermissions.isEmpty()) {
                new Handler(this.mLooper).post(new g(this));
            } else {
                return false;
            }
        } else if (permissions == Permissions.DENIED) {
            new Handler(this.mLooper).post(new h(this, permission));
        } else if (permissions == Permissions.NOT_FOUND) {
            this.shouldIgnorePermissionNotFound(permission);
            if (this.mPermissions.isEmpty()) {
                new Handler(this.mLooper).post(new Runnable() {
                    @Override
                    public final void run() {
                        PermissionsResultAction.this.onGranted();
                    }
                });
            } else {
                return false;
            }
        } else {
            return false;
        }
        return v0;
    }

    private synchronized boolean shouldIgnorePermissionNotFound(String arg4) {
        Logger.d(PermissionsResultAction.TAG, "Permission not found: " + arg4);
        return true;
    }
}

